package com.stone.serverless.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.stone.serverless.sdk.constant.EnvironmentConstant;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.PathResourceResolver;
import org.springframework.web.servlet.resource.ResourceResolverChain;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/22 20:28
 * @Version: 1.0.0
 */
public class ClassLoaderResourceResolver extends PathResourceResolver {

    private Map<String, Map<String, List<Object>>> componentNameMap;


    public void setComponentNameMap(Map<String, Map<String, List<Object>>> componentNameMap) {
        this.componentNameMap = componentNameMap;
    }

    public Map<String, Map<String, List<Object>>> getComponentNameMap() {
        return componentNameMap;
    }

    @Override
    protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) {

        Resource resource = super.resolveResourceInternal(request, requestPath, locations, chain);

        if (null != resource) {
            return resource;
        }
        String[] split = requestPath.split("/");
        String componentName = split[0];
        String version = split[1];

        if (MapUtil.isEmpty(componentNameMap)) {
            return resource;
        }
        Map<String, List<Object>> o = componentNameMap.get(componentName);
        if (ObjectUtil.isNull(o)) {
            return resource;
        }
        //version判断
        List<Object> listObj = o.get(version);
        if (CollUtil.isEmpty(listObj)) {
            return resource;
        }
        Object o1 = listObj.get(0);
        if (ObjectUtil.isNull(o1)) {
            version = EnvironmentConstant.DEFAULT_VERSION;
            o1 = o.get(version);
        }
        if (ObjectUtil.isNotNull(o1)) {
            //如果不为空尝试从这个classLoader里面加载
            String replace = requestPath.replace(componentName + "/", "").replace(version + "/", "");
            resource = new ClassPathResource(replace, o1.getClass().getClassLoader());
        }
        return resource;
    }

    @Override
    protected String resolveUrlPathInternal(String resourceUrlPath, List<? extends Resource> locations, ResourceResolverChain chain) {


        String s = super.resolveUrlPathInternal(resourceUrlPath, locations, chain);

        return s;
    }
}
